import { useEffect } from 'react';
import { Modal as AntdModal, Form, Input, message, Spin, Tag } from 'antd';
import { useRequest } from 'umi';
import moment from 'moment';
import ActionBuilder from '../builder/ActionBuilder';
import FormBuilder from '../builder/FormBuilder';
import { submitFieldsAdaptor, setFieldsAdaptor } from '../helper';
import styles from '../index.less';
const Modal = ({
  modalVisible,
  handleCancel,
  modalUri,
}: {
  modalVisible: boolean;
  handleCancel: (reload?: boolean) => void;
  modalUri: string;
}) => {
  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };
  const [form] = Form.useForm();
  const init = useRequest<{ data: BasicListApi.PageData }>(
    `https://public-api-v2.aspirantzhang.com${modalUri}?X-API-KEY=antd`,
    {
      manual: true,
      onError: () => {
        handleCancel();
      },
    },
  );

  const request = useRequest(
    (values: any) => {
      message.loading({ content: '加载中...', key: 'process', duration: 0 });
      const { uri, method, ...formValues } = values;
      return {
        url: `https://public-api-v2.aspirantzhang.com${uri}`,
        method,
        data: {
          ...submitFieldsAdaptor(formValues),
          'X-API-KEY': 'antd',
        },
      };
    },
    {
      manual: true,
      onSuccess: () => {
        message.success({
          content: '更新成功',
          key: 'process',
        });
        handleCancel(true);
      },
      formatResult: (res: any) => {
        return res;
      },
      throttleInterval: 1000,
    },
  );

  useEffect(() => {
    if (modalVisible) {
      init.run();
      form.resetFields();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [modalVisible]);

  useEffect(() => {
    if (init.data) {
      form.setFieldsValue(setFieldsAdaptor(init.data));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [init.data]);
  const onFinish = (values: any) => {
    request.run(values);
  };

  const actionHandler = (action: BasicListApi.Action) => {
    switch (action.action) {
      case 'submit':
        form.setFieldsValue({ uri: action.uri, method: action.method });
        form.submit();
        break;
      case 'cancel':
        handleCancel();
        break;
      case 'reset':
        form.resetFields();
        break;
      default:
        break;
    }
  };
  return (
    <AntdModal
      forceRender
      title={init?.data?.page?.title}
      visible={modalVisible}
      onCancel={() => {
        handleCancel();
      }}
      footer={ActionBuilder(init?.data?.layout?.actions[0]?.data, actionHandler, request.loading)}
      maskClosable={false}
    >
      {init.loading ? (
        <Spin className={styles.formSpin} tip="Loading..." />
      ) : (
        <>
          <Form
            form={form}
            {...layout}
            initialValues={{
              create_time: moment(),
              update_time: moment(),
              status: true,
            }}
            onFinish={onFinish}
          >
            {FormBuilder(init?.data?.layout?.tabs[0]?.data)}
            <Form.Item name="uri" key="uri" hidden>
              <Input />
            </Form.Item>
            <Form.Item name="method" key="method" hidden>
              <Input />
            </Form.Item>
          </Form>
          <Tag className={styles.formUpdateTime}>
            update_time:{moment(init.data?.dataSource?.update_time).format('YYYY-MM-DD HH:mm:ss')}
          </Tag>
        </>
      )}
    </AntdModal>
  );
};
export default Modal;
